package org.chen.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    @Value("${task.execution.pool.core-size:32}")
    private int corePoolSize;

    @Value("${task.execution.pool.max-size:64}")
    private int maxPoolSize;

    @Value("${task.execution.pool.queue-capacity:500}")
    private int queueCapacity;
    
    @Bean("commentTaskExecutor")
    public ThreadPoolTaskExecutor commentTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 根据16核64G配置适当的线程池大小
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        // 使用有界队列避免OOM
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("comment-executor-");
        // 使用CallerRunsPolicy避免任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 增加线程空闲时间，允许及时释放资源
        executor.setKeepAliveSeconds(60);
        // 允许核心线程超时，不活跃时释放
        executor.setAllowCoreThreadTimeOut(true);
        return executor;
    }

    @Bean("commentExecutor")
    public ThreadPoolTaskExecutor commentExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 根据16核64G配置适当的线程池大小
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        // 使用有界队列避免OOM
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("comment-executor-");
        // 使用CallerRunsPolicy避免任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 增加线程空闲时间，允许及时释放资源
        executor.setKeepAliveSeconds(60);
        // 允许核心线程超时，不活跃时释放
        executor.setAllowCoreThreadTimeOut(true);
        return executor;
    }
}